import { ZkxmTreeProps, ZkxmTreeEmits } from "./prop"
import { getYqlbList, getYqList, getZkpList } from '@api'
import { getJgZkpXm } from "@api/zkxm"
import { EventSure } from "@ui/utils/var"
import { zkspZdObj } from "@utils/dic"
import { SetupContext } from "vue"
export function use(props: ZkxmTreeProps, emit: SetupContext<ZkxmTreeEmits>['emit']): any {
  const prop = { label: 'mc', children: 'childs' }
    , nodeKeys = ref(['', ''])
  function getLbList() {
    return getYqlbList().then(({ data: { list } }) => {
      nodeKeys.value[1] = list[0] ? (list[0].lb || '') : ''
      return list.map(({ lb }) => {
        lb = lb || '-未设置'
        return { id: lb, mc: lb.split('-')[1] || '' }
      })
    })
  }
  function getYqInfo(node: any) {
    return getYqList({ lb: node.data.id }).then(({ data: { list } }) => {
      return (list || []).map(it => ({ id: it.id, mc: it.yqmc }))
    })
  }
  function getZkp(node: any) {
    return getZkpList({ yqid: node.data.id }).then(({ data: { list } }) => {
      return list
    })
  }
  function getXm(node: any) {
    const { yqid, id, mc, zkspdm } = node.data
    return getJgZkpXm({ yqid, zkpid: id }).then(({ data: { list } }) => {
      return list.map(it => ({ ...node.data, id: it.zbid, mc: it.zbmc, zkpid: id, zkpmc: mc, zkspdm_mc: zkspZdObj[zkspdm], zkgzdldm: it.zkgzdldm }))
    })
  }
  function loadNode(node: any, resolve: (data: any[]) => void) {
    switch (node.level) {
      case 0:
        return resolve([{ id: '', mc: props.mc || '测试', childs: [] }])
      case 1:
        return getLbList().then(resolve)
      case 2:
        return getYqInfo(node).then(resolve)
      case 3:
        return getZkp(node).then(resolve)
      case 4:
        return getXm(node).then(resolve)
      case 5:
        return resolve([])
    }
  }
  function handleNodeClick(a: any, b: any, c: any, d: any) {
    emit(EventSure, a, b, c, d)
  }
  return { prop, loadNode, handleNodeClick, nodeKeys }
}